package com.xj.edu.hotel.shiro;

import com.xj.edu.hotel.domain.Authority;
import com.xj.edu.hotel.domain.Manager;
import com.xj.edu.hotel.domain.Role;
import com.xj.edu.hotel.service.AuthorityService;
import com.xj.edu.hotel.service.ManagerService;
import com.xj.edu.hotel.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private ManagerService managerService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AuthorityService authorityService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo  = new SimpleAuthorizationInfo ();
        Manager manager =(Manager) principalCollection.getPrimaryPrincipal();//当前登录用户

        if(manager.getRoleId().equals("1")){
            authorizationInfo.addRole("超级管理员");
            List<Authority> authorities = authorityService.findAllPermission();
            for (Authority authority:authorities){
                authorizationInfo.addStringPermission(authority.getAuthorityType());
            }
        }else {
            for (Role role : roleService.findRoleByManagerId(manager.getManagerId())) {//通过id查找所有的角色
                authorizationInfo.addRole(role.getRoleType());//添加角色
                for (Authority authority : authorityService.findAuthorityByRoleId(role.getRoleId())) {//通过角色id查找所有权限
                    authorizationInfo.addStringPermission(authority.getAuthorityType());//添加权限
                }
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /**
         * 权限认证
         */
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        //获取账号
        String username = (String) usernamePasswordToken.getPrincipal();

        List<Manager> manager = managerService.findByName(username);
        if(manager.get(0) == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                manager,
                manager.get(0).getManagerPassword(),
                getName()
        );
        return authenticationInfo;
    }
}
